package main

import (
	"HumaTemplate/internal/middleware"
	"HumaTemplate/internal/models"
	"HumaTemplate/internal/routers"
	"context"
	"fmt"
	"github.com/danielgtaylor/huma/v2"
	"github.com/danielgtaylor/huma/v2/adapters/humago"
	"github.com/danielgtaylor/huma/v2/humacli"
	"net/http"
	"strconv"
	"time"
)

func main() {
	cli := humacli.New(func(hooks humacli.Hooks, opts *struct {
		Debug bool   `doc:"Enable debug logging"`
		Host  string `doc:"Hostname to listen on." short:"H" default:"localhost"`
		Port  int    `doc:"Port to listen on." short:"p" default:"18088"`
	}) {
		serverUrl := fmt.Sprintf("http://" + opts.Host + ":" + strconv.Itoa(opts.Port))
		prefix := "/api/v1"
		// Set up the router and API
		router := http.NewServeMux()
		openapiConfig := huma.DefaultConfig("My API", "1.0.0")
		openapiConfig.Info.Contact = &huma.Contact{
			Name:  "zzq",
			Email: "zhangzhanqi@iie.ac.cn",
		}
		openapiConfig.Servers = []*huma.Server{
			{URL: serverUrl + prefix},
		}
		api := humago.NewWithPrefix(router, prefix, openapiConfig)

		api.UseMiddleware(middleware.HumaTracing)

		huma.Get(api, "/ping",
			func(ctx context.Context, input *struct{}) (*models.HumaResponse[models.MessageResponse], error) {
				resp := &models.HumaResponse[models.MessageResponse]{
					Body: models.MessageResponse{
						Code:    200,
						Message: "pong",
					},
				}
				return resp, nil
			}, func(o *huma.Operation) {
				o.Summary = "Ping the server"
				o.Description = "This endpoint is used to check if the server is running."
				o.Tags = []string{"Ping"}
			})

		routers.APIRegister(api)

		// Create the HTTP server.
		server := http.Server{
			Addr:    fmt.Sprintf("%s:%d", opts.Host, opts.Port),
			Handler: router,
		}
		hooks.OnStart(func() {
			fmt.Println("Starting server on http://" + opts.Host + ":" + strconv.Itoa(opts.Port))
			server.ListenAndServe()
		})
		hooks.OnStop(func() {
			ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
			defer cancel()
			fmt.Println("Stopping server...")
			server.Shutdown(ctx)
		})
	})
	cli.Run()
}
